import { Component } from 'react'
import Taro from '@tarojs/taro'
import { View, Text } from '@tarojs/components'
import './index.scss'
import global from '../../global';
import { Button, Map, Swiper, SwiperItem, Picker, Input, Image } from '@tarojs/components'
import Request from '../../api/index'
import Utils from '../../utils'
import Event from '../../event';

export default class Index extends Component {

  constructor() {
    super();
    this.state = {
      form: {
        realName: '',
        idCard: '',
        regionId: '',
        regionName: '',
        villageId: '',
        villageName: '',
        buildingId: '',
        buildingName: '',
        unitId: '',
        unitName: '',
        houseId: '',
        houseName: ''
      },
      regions: [],
      villages: [],
      buildings: [],
      units: [],
      houses: [],
      loading: false,
      editable: true
    }
    this.linkMap = {
      region: {
        nextKey: 'village',
        resetKeys: [
          'village',
          'building',
          'unit',
          'house'
        ]
      },
      village: {
        nextKey: 'building',
        resetKeys: [
          'building',
          'unit',
          'house'
        ]
      },
      building: {
        nextKey: 'unit',
        resetKeys: [
          'unit',
          'house'
        ]
      },
      unit: {
        nextKey: 'house',
        resetKeys: [
          'house'
        ]
      },
      house: {
        nextKey: '',
        resetKeys: []
      }
    }
    this.submitForm = this.submitForm.bind(this)
    this.loadPickerData = this.loadPickerData.bind(this)
    this.checkAuthStatus = this.checkAuthStatus.bind(this)
  }

  componentWillMount () {

  }

  async componentDidMount () {
    await Taro.showLoading({
      title: "加载数据中...",
      mask: true
    })
   this.checkAuthStatus();
   await this.loadPickerData('region');
    await Taro.hideLoading();
  }

  componentWillUnmount () { }

  componentDidShow () { }

  componentDidHide () { }

  checkAuthStatus() {
    if (global.currentAuthInfo) {
      this.setState({
        form: global.currentAuthInfo,
        editable: false
      })
    }
  }

  async onPickerChange(key, val) {
    await Taro.showLoading({
      title: "加载数据中...",
      mask: true
    })
    if (this.state.form[key + 'Name'] === this.state[key + 's'][Number(val.detail.value)]['name']) {
      return;
    }
    let form = {
      ...this.state.form,
      [key + 'Name']: this.state[key + 's'][Number(val.detail.value)]['name'],
      [key + 'Id']: this.state[key + 's'][Number(val.detail.value)][key + 'Id']
    };

    if (this.linkMap[key]) {
      let resetData = {};
      this.linkMap[key].resetKeys.forEach(item => {
        form[item + 'Name'] = '';
        form[item + 'Id'] = '';
        resetData[item + 's'] = [];
      })
      this.setState({
        form,
        ...resetData
      });
      if (this.linkMap[key].nextKey) {
        await this.loadPickerData(this.linkMap[key].nextKey, form);
      }
      await Taro.hideLoading();
    }
  }

  async loadPickerData(type, param) {
    let url = `/business/${type}/list`;

    let paramStr = Utils.formatObjToParamStr(param);
    if (paramStr) {
      url += `?${paramStr}`;
    }
    let res = await Request.get(url);
    if (res.data.code !== 200) {
      throw new Error('获取下拉选项数据失败');
      return;
    }
    this.setState({
      [type + 's']: res.data.rows
    })
  }

  validateForm(form) {

    let _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
    let _IDre15 =  /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/

    if (!form.realName) {
      Taro.showToast({
        title: '请输入真实姓名！',
        icon: "error",
        duration: 1000
      });
      return false;
    }
    if (!form.regionId) {
      Taro.showToast({
        title: '请选择地区！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (!form.villageId) {
      Taro.showToast({
        title: '请选择小区！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    if (form.idCard && !(_IDRe18.test(form.idCard) || _IDre15.test(form.idCard))) {
      Taro.showToast({
        title: '请输入正确的身份证号！',
        icon: "error",
        duration: 1000
      })
      return false;
    }
    return true;
  }

  async submitForm() {
    if (this.state.loading) {
      return;
    }
    this.state.loading = true;
    this.setState({
      loading: true
    })
    let { form } = this.state;
    if (!this.validateForm(form)) {
      this.setState({
        loading: false
      });
      return;
    }
    form.wxUserName = global.userInfo.userName;
    form.wxUserId = global.userInfo.userId;
    try {
      let res = await Request.post('/business/auth_binding/apply', form);
      console.log(res)
      if (res.data.code !== 200) {
        throw new Error(res.data.msg);
      }
      await Taro.navigateBack();
      await Taro.showToast({
        title: '提交成功！',
        icon: "success",
        duration: 1000
      });
      Event.emit('updateList')
      Event.emit('loginFinish')
    } catch (e) {
      await Taro.showModal({
        title: e.toString()
      })
      // await Taro.showToast({
      //   title: e.toString(),
      //   icon: "error",
      //   duration: 1000
      // })
    } finally {
      this.setState({
        loading: false
      });
    }

  }


  render () {
    let { form, regions, villages, buildings, units, houses, loading, editable} = this.state;

    let msgComponent = <Text className='msg_container color-grey'>填入以下信息进行业主认证</Text>;

    if (form.status === '1') {
      msgComponent = <Text className='msg_container color-blue'>您的认证信息正在审核中</Text>;
    } else if (form.status === '2') {
      msgComponent = <Text className='msg_container color-green'>{global.userInfo.userName}，您已完成业主认证</Text>;
    } else if (form.status === '3') {
      msgComponent = <Text className='msg_container color-yellow'>您的认证信息已被驳回，请重新提交</Text>;
    } else if (form.status === '4') {
      msgComponent = <Text className='msg_container color-red'>您的认证信息已被废弃，请重新提交</Text>;
    }

    return (
      <View className='binding_container'>
        <View className='auth_msg_container'>
          {msgComponent}
        </View>
        <View className='input_item'>
          <Text className='required'>真实姓名</Text>
          <Input disabled={!editable} value={form.realName} onInput={(e) => {this.setState({form: {...form, realName: e.detail.value}})}} type='text' placeholder='请输入真实姓名'/>
        </View>
        <View className='input_item'>
          <Text>身份证号</Text>
          <Input disabled={!editable} value={form.idCard} onInput={(e) => {this.setState({form: {...form, idCard: e.detail.value}})}} type='text' placeholder='请输入身份证号'/>
        </View>
        <View className='input_item'>
          <Text className='required'>所在地区</Text>
          <Picker disabled={!editable} mode='selector' rangeKey={'name'} range={regions} onChange={(val) => this.onPickerChange('region', val)}>
            <Input value={form.regionName} type='text' disabled placeholder='请选择所在地区'/>
          </Picker>
          <Text className='iconfont icon-arrow-right size36'/>
        </View>
        <View className='input_item'>
          <Text className='required'>所属小区</Text>
          <Picker disabled={!editable || !form.regionName} mode='selector' rangeKey={'name'} range={villages} onChange={(val) => this.onPickerChange('village', val)}>
            <Input value={form.villageName} type='text' disabled placeholder='请选择所属小区(先选择地区)'/>
          </Picker>
          <Text className='iconfont icon-arrow-right size36'/>
        </View>
        <View className='input_item'>
          <Text>所属楼栋</Text>
          <Picker disabled={!editable} mode='selector' rangeKey={'name'} range={buildings} onChange={(val) => this.onPickerChange('building', val)}>
            <Input value={form.buildingName} type='text' disabled placeholder='请选择所属楼栋'/>
          </Picker>
          <Text className='iconfont icon-arrow-right size36'/>
        </View>
        <View className='input_item'>
          <Text>所属单元</Text>
          <Picker disabled={!editable} mode='selector' rangeKey={'name'} range={units} onChange={(val) => this.onPickerChange('unit', val)}>
            <Input value={form.unitName} type='text' disabled placeholder='请选择所属单元'/>
          </Picker>
          <Text className='iconfont icon-arrow-right size36'/>
        </View>
        <View className='input_item'>
          <Text>所属房屋</Text>
          <Picker disabled={!editable} mode='selector' rangeKey={'name'} range={houses} onChange={(val) => this.onPickerChange('house', val)}>
            <Input value={form.houseName} type='text' disabled placeholder='请选择所属房屋'/>
          </Picker>
          <Text className='iconfont icon-arrow-right size36'/>
        </View>
        {
          editable && <Button loading={loading} className='submit_btn' type='primary' onClick={this.submitForm}>提交</Button>
        }
        {
          editable && <View className='tips'>
            <Text className='iconfont icon-tanhao size40'/>
            <Text className='size28'> 提交申请后，我们尽快进行核实</Text>
          </View>
        }


      </View>
    )
  }
}
